package top.yokey.learn2.acyivity;

import android.Manifest;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.VideoView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatButton;
import androidx.appcompat.widget.AppCompatEditText;
import androidx.appcompat.widget.AppCompatImageView;
import androidx.core.content.FileProvider;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationData;
import com.bumptech.glide.load.resource.bitmap.VideoBitmapDecoder;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.XXPermissions;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import top.yokey.learn2.view.FileUtil;
import top.yokey.learn2.MyApp;
import top.yokey.learn2.R;
import top.yokey.learn2.ToastUtil;

public class LoginActivity extends AppCompatActivity {

    private AppCompatEditText mobileEditText;
    private AppCompatEditText passwordEditText;
    private AppCompatButton loginButton;
    private AppCompatButton cameraButton;
    private AppCompatButton camera1Button;
    private AppCompatButton cropButton;
    private AppCompatImageView mainImageView;
    private VideoView mainVideoView;

    private File mPhotoFile;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();

    private MapView mainMapView;
    public LocationClient mLocationClient = null;
    private MyLocationListener myListener = new MyLocationListener();
    private  File mPhotFile;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        mobileEditText = findViewById(R.id.mobileEditText);
        passwordEditText = findViewById(R.id.passwordEditText);
        loginButton = findViewById(R.id.loginButton);
        cameraButton = findViewById(R.id.cameraButton);
        camera1Button = findViewById(R.id.camera1Button);
        mainImageView = findViewById(R.id.mainImageView);
        cropButton = findViewById(R.id.cropButton);
        mainVideoView = findViewById(R.id.mainVideoView);

        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        option.setCoorType("bd09ll");
        option.setScanSpan(1000);
        option.setOpenGps(true);
        option.setLocationNotify(true);
        mLocationClient.setLocOption(option);
        mLocationClient.start();

        mLocationClient = new LocationClient(getApplicationContext());
        mLocationClient.registerLocationListener(myListener);
        mLocationClient.setLocOption(option);
        option.setIsNeedAddress(true);
        option.setNeedNewVersionRgc(true);


        /*
        ArrayList<String> arrayList = getFilesAllName("storage/emulated/0/Movies");
        for (int i = 0; i < arrayList.size(); i++) {
            if (arrayList.get(i).contains("123.mp4")) {
                File file = new File(arrayList.get(i));
                mainVideoView.setVideoURI(Uri.fromFile(file));
                mainVideoView.start();
            }
        }
        */

        String key = MyApp.get().getSharedPreferences().getString("key", "");
        if (!key.isEmpty()) {
            startActivity(new Intent(LoginActivity.this, MainActivity.class));
            finish();
        }

        loginButton.setOnClickListener(view -> {
            String mobile = mobileEditText.getText().toString();
            String password = passwordEditText.getText().toString();
            if (mobile.isEmpty() || password.isEmpty()) {
                ToastUtil.show(this, "请输入手机号或密码");
                return;
            }
            if (!isMobileNO(mobile)) {
                ToastUtil.show(this, "请输入有效手机号");
                return;
            }
            if (password.length() < 6) {
                ToastUtil.show(this, "密码长度不对");
                return;
            }
            OkGo.<String>post("https://demo.shopwt.com/api/mobile/index.php?w=login")
                    .params("username", mobile)
                    .params("password", password)
                    .params("client", "wap")
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(Response<String> response) {
                            try {
                                JSONObject jsonObject = new JSONObject(response.body().toString());
                                if (jsonObject.getInt("code") == 400) {
                                    jsonObject = jsonObject.getJSONObject("datas");
                                    ToastUtil.show(LoginActivity.this, jsonObject.getString("error"));
                                    return;
                                }
                                jsonObject = jsonObject.getJSONObject("datas");
                                String key = jsonObject.getString("key");
                                MyApp.get().getEditor().putString("key", key).apply();
                                ToastUtil.show(LoginActivity.this, "登录成功~");
                                startActivity(new Intent(LoginActivity.this, MainActivity.class));
                                finish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        });

        cameraButton.setOnClickListener(view -> {
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(intent, 999);
        });

        camera1Button.setOnClickListener(view -> {
            mPhotoFile = FileUtil.createFile(
                    getExternalMediaDirs()[0].getAbsolutePath(),
                    "learn2",
                    "jpg"
            );
            if (mPhotoFile != null) {
                Uri uri = FileProvider.getUriForFile(this, "top.yokey.learn2.fileProvider", mPhotoFile);
                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
                startActivityForResult(intent, 1000);
            }
        });

        cropButton.setOnClickListener(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("image/*");
            startActivityForResult(intent, 1001);
        });

        /*
        videoButton.setOnClickLister(view -> {
            Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            intent.setType("video/");
            startActivityForResult(intent, 1003);
        });
        */

    }

    public boolean isMobileNO(String mobiles) {
        Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
        Matcher m = p.matcher(mobiles);
        return m.matches();
    }

    private ArrayList<String> getFilesAllName(String path) {
        File file = new File(path);
        File[] files = file.listFiles();
        if (files == null) {
            return null;
        }
        ArrayList<String> list = new ArrayList<>();
        for (int i = 0; i < files.length; i++) {
            list.add(files[i].getAbsolutePath());
        }
        return list;
    }

    @Override
    protected void onResume() {
        super.onResume();
        String[] permission = new String[]{
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,
                Manifest.permission.CAMERA,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
        };
        XXPermissions.with(this).permission(permission).request(new OnPermissionCallback() {
            @Override
            public void onGranted(List<String> permissions, boolean all) {
                //用户允许权限申请
            }

            @Override
            public void onDenied(List<String> permissions, boolean never) {
                //用户拒绝了权限申请
                ToastUtil.show(LoginActivity.this, "用户拒绝了读取通讯录的权限");
            }
        });
    }




    @Override
    protected  void onPause() {
        super.onPause();
        mainMapView.onPause();

    }

    @Override
    protected  void onDestroy() {
        super.onDestroy();
        mainMapView.onDestroy();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 999) {
                Bitmap bitmap = data.getExtras().getParcelable("data");
                mainImageView.setImageBitmap(bitmap);
            }
            if (requestCode == 1000) {
                Log.d("TAGS", mPhotoFile.getAbsolutePath());
                mainImageView.setImageURI(Uri.fromFile(mPhotoFile));
                FileUtil.showInAlbum(this, mPhotoFile.getAbsolutePath());
            }
            if (requestCode == 1001) {
                mPhotoFile = FileUtil.createFile(
                        getExternalMediaDirs()[0].getAbsolutePath(),
                        "learn2",
                        "jpg"
                );
                Intent cropIntent = new Intent("com.android.camera.action.CROP");//跳到系统裁剪界面
                cropIntent.setDataAndType(data.getData(), "image/*");//设置裁剪图片的数据源
                cropIntent.putExtra("crop", "true");//设置裁剪
                cropIntent.putExtra("aspectX", 1);
                cropIntent.putExtra("aspectY", 1);
                cropIntent.putExtra("outputX", 500);
                cropIntent.putExtra("outputY", 500);
                cropIntent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());
                cropIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.parse("file://" + mPhotoFile.getAbsolutePath()));
                cropIntent.putExtra("return-data", "false");
                startActivityForResult(cropIntent, 1002);
                FileUtil.showInAlbum(this, mPhotoFile.getAbsolutePath());
            }
            if (requestCode == 1002) {
                mainImageView.setImageURI(Uri.fromFile(mPhotoFile));
            }
            if (requestCode == 1003) {
                Uri uri = data.getData();
                mainVideoView.setVideoURI(uri);
                mainVideoView.start();
            }
            if (requestCode == 1004) {
                Uri uri = data.getData();
                mainVideoView.setVideoURI(uri);
                mainVideoView.start();
            }
        }
    }

    class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation location) {
            double latitude = location.getLatitude();
            double longitude = location.getLongitude();
            float radius = location.getRadius();
            String coorType = location.getCoorType();
            int errorCode = location.getLocType();

            String addr = location.getAddrStr();
            String country = location.getCountry();
            String province = location.getProvince();
            String city = location.getCity();
            String district = location.getDistrict();
            String street = location.getStreet();    //获取街道信息
            String adcode = location.getAdCode();    //获取adcode
            String town = location.getTown();    //获取乡镇信息





                    Log.d("TAGS", latitude + "|" + longitude);
                    Log.d("TAGS", addr + "|" + country + "|" + province + "|" + city);
                }
            }
        }

